<template >
  <div>
    <dg-card class="add-box">
      <template slot="header">
        <div class="card-header" v-if="!modify">
          <div>{{ title }}</div>
          <div>
            <el-button v-permission="['XXXX_SUBMIT']" type="primary" @click="addExterCommun()">提交</el-button>
            <!-- 外部来文没有 保存草稿功能 -->
            <el-button v-permission="['XXXX_SUBMIT']" type="primary" @click="saveExterCommun()" v-if="sourceType != 0"
              >保存</el-button
            >
            <el-button @click="onCloseAdd">关闭</el-button>
          </div>
        </div>
      </template>
      <div>
        <div class="add-table-box">
          <div class="add-form">
            <basic-info :id="id" ref="form" :source-type="sourceType" @handleCasePeople="(v) => (peopleList = v)" />
          </div>
          <div class="list-info">
            <case-list :id="id" ref="case" @saveInfo="addExterCommun" :people-list="peopleList" />
            <!-- 关联信息 -->
            <related-info
              :id="id"
              :isCheckSelectAuth="false"
              :columnData="glxxColumns"
              @saveInfo="addExterCommun"
              ref="relatedInfo"
            />
            <!-- 关联专题 -->
            <related-special :id="id" @saveInfo="addExterCommun" ref="relatedSpecial" />
          </div>
        </div>
      </div>
    </dg-card>
  </div>
</template>
<script>
import { addProcess } from '@/api/common';
import { mapState } from 'vuex';
import BasicInfo from './components/BasicInfo';
import CaseList from './components/CaseList';
import RelatedInfo from './components/RelatedInfo';
import RelatedSpecial from './components/RelatedSpecial';
import { BM_DEPT } from '@/common/codeDic';
export default {
  name: 'AddExterCommun',
  components: {
    BasicInfo,
    CaseList,
    RelatedInfo,
    RelatedSpecial
  },
  props: {
    // 编辑主流程id
    flowId: {
      type: String
    },
    title: {
      type: String,
      default: '外部来文新增'
    },
    // 0-外部来文；1-要情上报；2-线索上报；3-110报警信息（情报）-研判；4-线索（情报特有）；5-110报警处理
    sourceType: {
      type: String,
      default: '0'
    },
    // 是否为修改，修改和编辑页面不一样
    modify: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: '',
      peopleList: [],
      glxxColumns: [
        { label: '序号', type: 'index', width: 70 },
        { label: '操作', type: 'operate' },
        { label: '上报时间', prop: 'sendTime' },
        {
          label: '信息编号',
          prop: 'serialNo',
          isLink: true, // 是否是链接
          openUrl: 'ImpDetail', // 打开路径
          width: 200
        },
        { label: '标题', prop: 'title' },
        { label: '上报单位', prop: 'createOrgCode', code: BM_DEPT }
      ],
      // 是否已上报
      isReport: false
    };
  },
  computed: {
    ...mapState(['constant'])
  },
  created() {
    this.init();
    // 获取来文单位,信息类别
    // 获取信息类别
    this.$store.dispatch('getConstant', ['BM_LWDW', 'BM_WKLX', 'DM_SEX', 'BM_QTLB_QTXX']);
    this.$store.dispatch('getConstantTree', ['BM_XXLB', 'BM_ZXDD', 'BM_DEPT']);
  },
  methods: {
    /**
     * 初始化 编辑获取详情，新增创建流程id
     */
    init() {
      if (this.flowId) {
        this.id = this.flowId;
        this.isReport = true;
      }
    },
    /**
     * 新增外部来文
     * isDraft是否为草稿 1是草稿,草稿不做校验 0不是草稿
     * ifGoback 是否返回上一个页面 1是 0不是
     * from 页面内保存，触发组件
     */
    async addExterCommun(isGoback = 1, isDraft = '0', from) {
      let that = this;
      // 获取表单数据
      let form = await this.$refs.form.onValidForm(isDraft);
      // 获取案件人员信息
      let asjryxxList = await this.$refs.case.onValidIdcard(isDraft);
      const loadingInstance = this.$loading({
        lock: true,
        text: '保存中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      // 新增的关联信息
      let glxxList = this.$refs.relatedInfo.allRelated.map((item) => {
        console.log(' this.$refs.relatedInfo.allRelated', this.$refs.relatedInfo.allRelated);
        return {
          // 因为三种数据类型（后端返回的、系统推荐、手动关联），如果有targetFlowId，就传targetFlowId；如果没有就传targetFlowId
          gldxId: item.targetFlowId ? item.targetFlowId : item.id,
          gldxType: '1'
        };
      });

      // 新增的专题信息
      let ssztList = this.$refs.relatedSpecial.allRelated.map((item) => {
        return {
          gldxId: item.id,
          gldxType: '2'
        };
      });
      // 保存基本信息
      addProcess({
        sourceType: this.sourceType,
        ...form,
        isDraft: isDraft,
        id: ['3', '5'].includes(this.sourceType) ? '' : this.id,
        xxlbCode: form.xxlbCode
          ? Array.isArray(form.xxlbCode)
            ? form.xxlbCode[form.xxlbCode.length - 1]
            : form.xxlbCode
          : '',
        zxdd: form.zxdd && Array.isArray(form.zxdd) ? form.zxdd[form.zxdd.length - 1] : form.zxdd, // 指向地点是单选
        asjryxxList,
        glxxList,
        ssztList,
        jqxxbh: ['3', '5'].includes(this.sourceType) ? this.id : '',
        asjryxxDeleteList: this.$refs.case.asjryxxDeleteList,
        zljsId: this.sourceType === '5' ? this.$route.params.zlid : ''
      })
        .then(({ data }) => {
          if (isGoback) {
            that.$router.go(-1);
          } else {
            that.id = data.id;
            that.$refs.relatedInfo.handleId(that.id, from);
            that.$refs.relatedSpecial.handleId(that.id, from);
            that.$refs.case.handleId(that.id, from);
          }
          that.isReport = true;
          that.$message.success('保存基本信息成功');
          loadingInstance.close();
        })
        .catch((err) => {
          this.$message.warning('保存基本信息出错');
          loadingInstance.close();
          return;
        });
    },
    /**
     * 如果是普通页面，保存草稿，如果是待上报页面的保存，直接上报
     */
    saveExterCommun() {
      this.addExterCommun('1', '1');
    },

    /**
     * 删除草稿
     */
    onDeleteProcess() {
      addProcess({ id: this.id, isDelete: '1' }).then((data) => {
        this.$router.go(-1);
      });
    },
    /**
     * 关闭新增页面
     */
    onCloseAdd() {
      // 没上报，存储为草稿
      if (!this.isReport) {
        this.$confirm('是否保存为草稿?', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '关闭',
          type: 'warning'
        })
          .then(() => {
            this.saveExterCommun();
          })
          .catch(() => {
            this.$router.go(-1);
          });
      } else {
        this.$router.go(-1);
      }
    }
  }
};
</script>
<style scoped lang='scss'>
.add-box {
  .card-header {
    display: flex;
    justify-content: space-between;
  }
}
.add-table-box {
  /deep/.el-card__header {
    padding: 1rem 0;
  }
  /deep/.el-card__body {
    padding: 1rem 0;
  }
  background: #fff;
  /deep/.el-divider--horizontal {
    margin: 10px 0;
  }
  .operater {
    display: flex;
    .upload {
      margin: 0 6px;
    }
  }
  .list-info > div {
    margin-top: 20px;
  }
  .title-operater {
    display: flex;
    justify-content: space-between;
  }
  /deep/.valid-box {
    display: flex;
    align-items: center;
    .el-icon-warning {
      color: #f56c6c;
      margin-right: 10px;
      font-size: 16px;
    }
  }
  .input-select {
    display: flex;
    margin-bottom: 12px;
    .btngroup {
      display: flex;
      width: 30%;
      margin-left: 8px;
      .sub {
        width: 32px;
        height: 32px;
        min-width: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .el-select {
      /deep/.el-input {
        width: 110px;
        input {
          padding-right: 12px;
        }
      }
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>


